#!/usr/local/bin/perl -w
use strict;

my $PI = 2 * atan2(1,1);

my @m = qw(
			health 	damage	speed	accuracy	vulner	mobility	stealth	aiming	spread	square
);
my $data = [
[qw(grena	200		50		1		1			1		1			5		20		50		50		)],
[qw(storm	200		25		1		1			1		40			1		40		70		10		)],
[qw(snipe	200		20		1		20			1		1			10		90		90		1		)],
[qw(chass	200		25		1		1			60		1			15		50		70		1		)],
[qw(shoot	200		30		80		1			1		1			20		30		50		1		)],
];
my %all;
for(@$data){
	my $u = shift @$_;
	@{$all{$u}}{@m} = @$_;
}
sub dev {
	my ($v1,$v2) = @_;
	return atan2($v2,$v1)/$PI > 1;
}
#=(СТЕПЕНЬ(A4;1/$B$2)*$B$2+A4/$B$1)/$B$2
sub disp {
	my $val = shift;
	my $r = rand();
	my $k = (($r**(1/3))*3 + $r/5) / 3;
	return $val * $k;
}
sub calc {
	#если !подвижность
	#	попал = (прицельность - маскировка)
	#если !попал
	#	если площадь
	#		попал = 1
	#если попал
	#	если точность
	#		урон = остаток жизни
	#	нет
	#		урон = дамаг * разброс * уязвимость
	#нет
	#	урон = 0
	my ($u1,$u2) = @_;
	my $hit;
	if(rand(100) < $u2->{mobility}){
		$hit = dev($u1->{aiming},$u2->{stealth});
	}
	unless($hit){
		$hit = rand(100) < $u1->{square}
	}
	my $damag = 0;
	if($hit){
		if(rand(100) < $u1->{accuracy}){
			$damag = $u2->{current};
		}else{
			$damag = disp($u1->{damage}) * disp($u1->{spread})/100 * disp($u1->{vulner})/100;
		}
	}
	if($damag > $u2->{current}){
		$damag = $u2->{current};
	}
	$u2->{current} -= $damag;
	return $damag;
}
my $k = 0.3;
sub calc2 {
	my ($u1,$u2) = @_;
	my $hit = dev($u1->{aiming},$u2->{stealth}+$u2->{mobility});
	#$hit = rand();
	my $damag;
	if($hit < $k){
		$damag = $u1->{damage} * rand($u1->{square}*2)/100;
	}else{
		$damag = $u1->{damage} * rand($u1->{spread}*2)/100;
	}
	if(rand(100) < $u1->{accuracy}){
		$damag = $u2->{current};
	}
	if(rand(100) < $u2->{vulner}){
		$damag = 0;
	}
	if($damag > $u2->{current}){
		$damag = $u2->{current};
	}
	$u2->{current} -= $damag;
	return $damag;
}
sub hit {
	my ($u1,$u2) = @_;
	$u1->{_speed} = $u1->{speed};
	{
		calc($u1,$u2);
		if($u2->{current} <= 0){
			return 0;
		}
		if(rand(100) < $u1->{_speed}){
			$u1->{_speed} /= 2;
			redo;
		}
	}
	return 1;
}
sub turn {
	my ($u1,$u2) = @_;
	my $turn = 0;
	{
		$turn++;
		if(hit($u1,$u2) and $turn < 100){
			redo;
		}
	}
	return $turn;
}
sub test2 {
	my ($u1,$u2) = @_;
	($u1,$u2) = ($all{$u1},$all{$u2});
	$u2->{current} = $u2->{health};
	return calc($u1,$u2);
}
print test2("grena","storm"),"\n";

__END__
my @all = keys %all;
print join("\t","all",@all),"\n";
for my $u1(@all){
	print $u1;
	for my $u2(@all){
		my $res = test($all{$u1},$all{$u2},1000);
		print "\t",$res;
	}
	print "\n";
}
